from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
# from utils.sendmobilemessage import send_message
from celerytasks.smstasks import send_message
import redis
from rest_framework.response import Response
import json
from .models import User,Role
from rest_framework_jwt.utils import jwt_encode_handler, jwt_payload_handler
from django.contrib.auth import authenticate
import time
from rest_framework.viewsets import ModelViewSet
from .serializers import UsersSer
from django.utils import timezone
from django.db.models import Q



"""
注册新账号就相当于登录
    1.手机号不能重复注册
    2.注册时发送短信验证码
    3.输入短信验证码
    4.点击登录
        1.校验：短信验证码是否一样
        2.把用户信息写入数据库
        3.写入token， 记录当前用户信息的状态
"""
class SmsCode(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        # print("111.",mobile)
        # 调用方法
        result = send_message(mobile)
        if result['statusCode'] == '172001':
            return Response({'msg':'网络错误','code':'400'})
        elif result['statusCode'] == '160038':
            return Response({'msg':'验证码过于频繁','code':'400'})
        else:
            return Response({'msg': '欧克','code':'200'})



class Login(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        pwd = request.data.get('password')
        sms_code = request.data.get('code')
        account = request.data.get('username')
        print('手机号',mobile,pwd,sms_code,account)
        # 使用当前手机号发送短信验证码
        # result = send_message('mobile')\login_form

        # if result.statusCode !=
        #     return Response({'msg':'网络错误','code':'400'})
            # 校验银行输入的短信验证码和redis中是否一

        redis_cli = redis.Redis(db=2, password=12345)
        data = redis_cli.get("sms_%s"%mobile)

        '''
        # resp = sdk.sendMessage(sms_code, mobile, datas)
        # resp = json.loads(resp)
        # print('resp》》》',resp)
        '''
        if data:
            # 取redis中的验证码
            redis_code = data.decode('utf-8')
            if redis_code == sms_code:
                # 写入数据库
                user = User.objects.create(username=account,password=pwd,phone=mobile)
                # print(user)
                # TODO 登录成功写入token
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                return Response({'msg':'ok','code':'200','user':user.username,'token':token})
            else:
                return Response({'msg':'验证码错误','code':'400 '})
        else:
            return Response({"msg": "验证码以过期", "code": "401"})
        # else:
        #     return Response({'msg':'验证码已经过期','code':'400'})
        # try:
        #     #  写入数据库
        #     user = User.objects.create(username=account,password=pwd)
        #     # TODO 登录成功写入token
        #     payload = jwt_payload_handler(user)
        #     token = jwt_encode_handler(payload)
        #     return Response({'msg':'ok','code':'200','user':user.username,'token':token})
        # except Exception as e:
        #     print(e)



# 用户的增删改查
class UsersView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UsersSer
    lookup_field = "pk"
    lookup_url_kwarg = "id"


# 获取用户总人数
class UsersCountView(APIView):
    def get(self,request):
        num = User.objects.all().count()
        return Response({'count':num})


# 日增用户
class DaliAddUserView(APIView):
    def get(self,request):
        # 获取当前的时间
        date = time.strftime("%y-%m-%d")
        print(date)
        # 根据当前时间过滤用户，获取用户数量
        num = User.objects.filter(date_joined__contains = date).count()
        return Response({'count':num})



# 日活跃用户
class DalyLiveUserView(APIView):
    def get(self,request):
        date = time.strftime("%y-%m-%d")
        print(date)
        # 根据当前时间过滤用户，获取用户数量
        num = User.objects.filter(last_login__contains=date).count()
        return Response({'count':num})



class UserAdd(APIView):
    def post(self,request):
        # role = request.data.get("role_id")
        # username = request.data.get('username')
        # password = request.data.get('password')
        # phone = request.data.get('phone')
        # email = request.data.get('email')
        # try:
        #     role = Role.objects.get(name=role)
        # except Exception as e:
        #     return Response({'msg':'没有该角色','code':'402'})
        #
        # user = User.objects.create(
        #     username=username,
        #     password=password,
        #     phone=phone,
        #     email=email,
        #     date_joined=timezone.now(),
        #     last_login=timezone.now()
        # )
        # user.role.add(role.id)
        # return Response({'msg':'添加成功','code':'200'})
        print(request.data)
        user = User()
        role = Role()
        user.username=request.data['username']
        user.password=request.data['password']
        user.phone = request.data['phone']
        user.email = request.data['email']
        role.name = request.data['role']
        role.save()
        user.role_id = role.id
        user.save()
        return Response({"msg":"ok"})



class SearchGoods(APIView):
    "搜索"
    def post(self, request):
        # 获取搜索的内容
        search = request.query_params.get('keyword')
        # 根据信息查询
        user = User.objects.get(Q(phone__contains=search) | Q(username__contains=search))
        print(user)
        if user:
            ser = UsersSer(user, many= True)
            return Response({'user':ser.data})
        return Response({'msg':'用户不存在'})